package cn.ondraw.ragflow.service.impl;

import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import cn.ondraw.ragflow.pojo.request.ChatNonStreamResponse;
import cn.ondraw.ragflow.pojo.request.ChatRequest;
import cn.ondraw.ragflow.pojo.request.ChatStreamResponse;
import cn.ondraw.ragflow.service.OpenAICompatibleService;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

/**
 *
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OpenAICompatibleServiceImpl implements OpenAICompatibleService {
    private final PythonApiCaller pythonApiCaller;


    /**
     * 创建非流式聊天完成请求
     *
     * @param chatId  聊天 ID
     * @param request 聊天请求对象
     * @return 非流式聊天响应对象
     */
    @Override
    public ChatNonStreamResponse createChatCompletion(String chatId, ChatRequest request) {
        ResponseEntity<?> response = pythonApiCaller.callPostApi("/api/v1/chats_openai/" + chatId + "/chat/completions", request);
        return JSONUtil.toBean(response.getBody() != null ? response.getBody().toString() : null, ChatNonStreamResponse.class, true);
    }

    /**
     * 创建流式聊天完成请求
     *
     * @param chatId  聊天 ID
     * @param request 聊天请求对象
     * @return 流式聊天响应对象
     */
    @Override
    public ChatStreamResponse createChatCompletionStream(String chatId, ChatRequest request) {
        ResponseEntity<?> response = pythonApiCaller.callPostApi("/api/v1/chats_openai/" + chatId + "/chat/completions", request);
        return JSONUtil.toBean(response.getBody() != null ? response.getBody().toString() : null, ChatStreamResponse.class, true);
    }

    /**
     * 创建非流式代理完成请求
     *
     * @param agentId 代理 ID
     * @param request 聊天请求对象
     * @return 非流式聊天响应对象
     */
    @Override
    public ChatNonStreamResponse createAgentCompletion(String agentId, ChatRequest request) {
        ResponseEntity<?> response = pythonApiCaller.callPostApi("/api/v1/agents_openai/" + agentId + "/chat/completions", request);
        return JSONUtil.toBean(response.getBody() != null ? response.getBody().toString() : null, ChatNonStreamResponse.class, true);
    }

    /**
     * 创建流式代理完成请求
     *
     * @param agentId 代理 ID
     * @param request 聊天请求对象
     * @return 流式聊天响应对象
     */
    @Override
    public ChatStreamResponse createAgentCompletionStream(String agentId, ChatRequest request) {
        ResponseEntity<?> response = pythonApiCaller.callPostApi("/api/v1/agents_openai/" + agentId + "/chat/completions", request);
        return JSONUtil.toBean(response.getBody() != null ? response.getBody().toString() : null, ChatStreamResponse.class, true);
    }
}
